package com.zang.blogz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zang.blogz.constant.ResultConstant;
import com.zang.blogz.entity.Photo;
import com.zang.blogz.entity.PhotoAlbum;
import com.zang.blogz.mapper.PhotoAlbumMapper;
import com.zang.blogz.model.output.PhotoVO;
import com.zang.blogz.model.output.admin.AdminPhotoAlbumVO;
import com.zang.blogz.result.Result;
import com.zang.blogz.service.PhotoAlbumService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zang.blogz.service.PhotoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 相册 服务实现类
 * </p>
 *
 * @author 朵橙i
 * @since 2022-06-17
 */
@Service
public class PhotoAlbumServiceImpl extends ServiceImpl<PhotoAlbumMapper, PhotoAlbum> implements PhotoAlbumService {

    @Autowired
    private PhotoService photoService;

    @Autowired
    private PhotoAlbumMapper photoAlbumMapper;

    @Override
    public PhotoVO photoList(Integer albumId) {

        PhotoVO photoVo = new PhotoVO();

        BeanUtil.copyProperties(getById(albumId), photoVo) ;

        List<Photo> photos = photoService.photoList(albumId);

        photoVo.setPhotos(photos);

        return photoVo;
    }

    @Override
    public IPage<AdminPhotoAlbumVO> photoAlbumListAdmin(Page<AdminPhotoAlbumVO> page) {

        return photoAlbumMapper.photoAlbumListAdmin(page);

    }

    @Override
    public Result<PhotoAlbum> saveOrUpdatePhotoAlbum(PhotoAlbum photoAlbum) {

        PhotoAlbum album = getById(photoAlbum.getId());

        if (photoAlbum.getId() == null || album == null){

            save(photoAlbum);
            return Result.ok(ResultConstant.SAVE_SUCCESS,photoAlbum) ;
        }else {

            updateById(photoAlbum);
            return Result.ok(ResultConstant.UPDATE_SUCCESS,photoAlbum) ;
        }


    }

    @Override
    public Result<String> deletePhotoAlbum(Integer photoAlbumId) {

        Boolean albumIsNull = photoService.photoAlbumIsNull(photoAlbumId);

        if (albumIsNull){
            throw new RuntimeException("当前相册下存在照片不能删除");
        }

        removeById(photoAlbumId);

        return Result.ok(ResultConstant.DELETE_SUCCESS);
    }
}
